1.1

Implement an algorithm to determine if a string has all unique characters.


In [3]:
def is_unique_string(string):
    chars_seen = set()
    for char in string:
        if char in chars_seen:
            return False
        chars_seen.add(char)
    return True

In [9]:
unique_string = "abcdefghi"
usual_string = "abcdeefg"
print(is_unique_string(unique_string))
print(is_unique_string(usual_string))


True
False

1.2

Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.

Note: Interviewing using Python so going to do this as a regular reverse a string function


In [27]:
def reverse_string(string):
    r_string = ""
    for i in xrange(len(string)-1, -1, -1):
        r_string += string[i]
    return r_string

In [28]:
string = "abcdef"
print(reverse_string(string))


fedcba

1.3

Given two strings, write a method to decide if one is a permutation of the other.


In [31]:
def is_permutation(string1, string2):
    if len(string1) != len(string2):
        return False
    if sorted(string1) == sorted(string2):
        return True

In [33]:
string1 = "abc"
string2 = "bca"
string3 = "abcd"
print(is_permutation(string1, string2))
print(is_permutation(string1, string3))


True
False

1.4

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

EXAMPLE

Input: "Mr John Smith"

Output: "Mr%20John%20Smith"


In [47]:
def replace_spaces(string):
    for i in xrange(len(string)):
        if string[i] == " ":
            string = string[:i] + "%20" + string[i+1:]
    return string

In [48]:
string = '"Mr John Smith\t"'
print(string)
print(replace_spaces(string))


"Mr John Smith	"
"Mr%20John%20Smith	"

1.5

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string "aabcccccaaa" would become "a2b2c5a3". If the compressed string would not be smaller than the original string, your method should return the original string.


In [91]:
def compress_string(string):
    new_string = ""
    current = string[0]
    count = 0
    for char in string:
        if char == current:
            count += 1
        else:
            new_string += "{0}{1}".format(current, count)
            current = char
            count = 1
    new_string += "{0}{1}".format(current, count)
    if len(new_string) >= len(string):
        return string
    return new_string

In [93]:
print(compress_string("aabbcccccaaa"))
print(compress_string("a"))


a2b2c5a3
a

In [ ]: